package com.imonsoft.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * 
 * @author liuzg
 * 2011-07-19
 * 邮件发送
 */
public class MailUtils  implements Runnable {
	private String to; // 接收方
	private String subject; // 标题
	private String content; // 邮件内容
	private Thread thread; // 定义线程
	private String sname; // 邮件署名
	@SuppressWarnings("rawtypes")
	private List attach;
	private String type = "text/html"; // or text/plain 发送邮件的格式
	private String smtpHost; // 邮件服务器 smtp.163.com等
	private String emailFrom; // 发送方邮箱
	private String fromPwd; // 密码
	private String mailserver;
	private String from;
	/**
	 * @return the from
	 */
	public String getFrom() {
		return from;
	}

	/**
	 * @param from the from to set
	 */
	public void setFrom(String from) {
		this.from = from;
	}

	private String pwd;

	/**
	 * @return the mailserver
	 */
	public String getMailserver() {
		return mailserver;
	}

	/**
	 * @param mailserver the mailserver to set
	 */
	public void setMailserver(String mailserver) {
		this.mailserver = mailserver;
	}

	/**
	 * @return the pwd
	 */
	public String getPwd() {
		return pwd;
	}

	/**
	 * @param pwd the pwd to set
	 */
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	/**
	 * 带模版的邮件
	 * @param to 邮件接收地址
	 * @param subject 邮件标题
	 * @param content 邮件内容
	 * @param fileName 邮件模板名称（带地址）
	 */
	@SuppressWarnings("rawtypes")
	public MailUtils(String to, String subject, String content,
			String fileName) {
		try {
			if (to != null && !"".equals(to)) {
				thread = new Thread(this);
				this.to = to;
				this.subject = subject;
				attach = new ArrayList();
				// 读取文件模板
				File file = new File(fileName);
				BufferedReader br = new BufferedReader(new FileReader(file));
				StringBuffer sb = new StringBuffer();
				while (br.ready()) {
					sb.append(br.readLine());
					sb.append("\r\n");
				}
				// 賛换模块中的##content变量内容为content
				this.content = sb.toString().replaceAll("##content", content);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	} 
	 
	/**
	 * 带上署名和模块的邮件
	 * @param sname
	 * @param to
	 * @param subject
	 * @param content
	 * @param fileName 
	 */
	@SuppressWarnings("rawtypes")
	public MailUtils(String sname, String to, String subject,
			String content, String fileName,String mailserver,String from,String pwd) {
		try {
			thread = new Thread(this);
			this.to = to;
			this.subject = subject;
			this.sname = sname;
			attach = new ArrayList();
			this.mailserver=mailserver;
			this.from=from;
			this.pwd=pwd;

			// 读取文件模板
			File file = new File(fileName);
			BufferedReader br = new BufferedReader(new FileReader(file));
			StringBuffer sb = new StringBuffer();
			while (br.ready()) {
				sb.append(br.readLine());
			}
			this.content = sb.toString().replaceAll("##caicainet_content",
					content);

		} catch (Exception e) {
			e.printStackTrace();
		}

	} 
	 
	/**
	 * 普通邮件发送，不带附件
	 * @param sname 发件人名称
	 * @param to 收件人
	 * @param subject 邮件标题
	 * @param content 邮件内容
	 * @param typeId 标记
	 */
	@SuppressWarnings("rawtypes")
	public MailUtils(String sname, String to, String subject,
			String content, int typeId,String mailserver,String from,String pwd) {
		thread = new Thread(this);
		this.to = to;
		this.subject = subject;
		this.sname = sname;
		attach = new ArrayList();
		this.content = content;
		this.type = "text/plain";
		this.mailserver=mailserver;
		this.from=from;
		this.pwd=pwd;
	} 
	 
	public void run() {
		try {
			send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	 
	public void start() {
		thread.start();
	}

	public boolean send() throws Exception {
		return send(to, subject, content,mailserver,from,pwd);
	}
	
	/**
	 * 邮件发送
	 * @param to
	 * @param subject
	 * @param content
	 * @return
	 */
	 private boolean send(String to, String subject, String content,String mailserver,String From,String pwd) {
		boolean blnResult = false;
		InternetAddress[] address = null;
		// mailserver邮件服务器 Form 发送邮件的邮箱 pwd密码
		// 此处三个参数可能通过数据库或.properties等方式来获取，方便后期的管理与设置
//		String mailserver = "smtp.qq.com";
//		String From = "64925141@qq.com";// 发送方的邮箱
//		String pwd = "wangxin";// 密码

		if (smtpHost != null && !"".equals(smtpHost))
			mailserver = smtpHost;
		if (emailFrom != null && !"".equals(emailFrom))
			From = emailFrom;
		if (fromPwd != null && !"".equals(fromPwd))
			pwd = fromPwd;

		if (smtpHost != null && "nopass".equals(smtpHost)) {
			smtpHost = "";
			System.out.println("发送给" + to + "失败！原因是smtp地址不正确");
			return false;
		}

		String messageText = content;

		boolean sessionDebug = false;
		Date d1 = new Date();
		try {
			// 设定所要用的Mail 服务器和所使用的传输协议
			java.util.Properties props = System.getProperties();
			props.put("mail.smtp.host", mailserver);
			props.put("mail.transport.protocol", "smtp");
			//props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证
			props.put("mail.smtp.starttls.enable","true");
			props.put("mail.smtp.debug", "true");

			if(mailserver.indexOf("smtp.gmail.com")>=0) {
				props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
				props.put("mail.smtp.socketFactory.fallback", "false"); 
				props.put("mail.smtp.port", "465"); 
				props.put("mail.smtp.socketFactory.port", "465"); 
            }
			//SecurityManager security = System.getSecurityManager();
			// 产生新的Session 服务
			javax.mail.Session mailSession = javax.mail.Session
					.getDefaultInstance(props, null);
			mailSession.setDebug(sessionDebug);
			Message msg = new MimeMessage(mailSession);
			if (sname != null && !"".equals(sname)) {
				// 设定发邮件的人
				msg.setFrom(new InternetAddress(From, sname));
			} else {
				// 带署名的邮件
				msg.setFrom(new InternetAddress(From, "jinhetech"));
			}

			if (sname != null && "mail".equals(sname)) {
				msg.setFrom(new InternetAddress(From, ""));
			}

			// 设定收信人的信箱
			address = InternetAddress.parse(to, false);
			msg.setRecipients(Message.RecipientType.TO, address);

			// 设定信中的主题
			msg.setSubject(subject);

			// 设定送信的时间
			msg.setSentDate(new Date());

			if ("text/html".equals(this.type)) {
				msg.setContent(messageText, type + ";charset=GB2312");
			} else {
				msg.setText(messageText);
			}

			Transport transport = mailSession.getTransport("smtp");

			transport.connect(mailserver, From, pwd);
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
			Date d2 = new Date();
			System.out.println("发送给" + to + "成功！耗时"
					+ (d2.getTime() - d1.getTime()) + "毫秒,发送方：" + From);
			blnResult = true;

		} catch (MessagingException mex) {
			mex.printStackTrace();
			blnResult = false;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return blnResult;
	}
	public void setTo(String to) {
		this.to = to;
	}

	public String getTo() {
		 return this.to;
	}

	public void setSubject(String subject) {
		 this.subject = subject;
	}

	public String getSubject() {
		 return this.subject;
	}

	public void setContent(String content) {
		 this.content = content;
	}

	public String getContent() {
		 return this.content;
	}

	@SuppressWarnings("unchecked")
	public void addAttach(String file) {
		attach.add(file);
	}

	public boolean isAttach() {
		return attach != null && attach.size() > 0;
	}
	 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
//			String mailserver = "smtp.qq.com";
//			String From = "64925141@qq.com";// 发送方的邮箱
//			String pwd = "wangxin";// 密码
			// 普通的文字邮件
//			MailUtils sendMail = new MailUtils("发件人", "64925141@qq.com", "64925141@qq.com",
//					"邮件测试内容",1,"smtp.qq.com","64925141@qq.com","wangxin");
//			sendMail.start();
			
			
			
//			String sname, String to, String subject,
//			String content, String fileName,String mailserver,String from,String pwd
			
			 //带模版的邮件
			 String path = "D:/QQ截图20130606110247.png";
			 //获取存放路径
			 //String chtml="";
			 MailUtils sendMail=new MailUtils("发件人", "64925141@qq.com", "64925141@qq.com","邮件测试内容",path,"smtp.qq.com","64925141@qq.com","wangxin");
			 sendMail.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


}
